﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using BookiFramework.Abstracts.Security;

namespace BookiFramework.Security.Cryptography
{
    public class AESRijndaelCrypter : ICrypter
    {
        readonly byte[] _key;

        readonly byte[] _iv;

        public AESRijndaelCrypter(string key, string iv)
        {
            _key = Encoding.ASCII.GetBytes(key);
            _iv = Encoding.ASCII.GetBytes(iv);
        }

        public byte[] Crypt(string text)
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(text);
            byte[] encripted;

            var cripto = new RijndaelManaged();

            using (var ms = new MemoryStream(inputBytes.Length))
            {
                using (var objCryptoStream = new CryptoStream(ms, cripto.CreateEncryptor(_key, _iv), CryptoStreamMode.Write))
                {
                    objCryptoStream.Write(inputBytes, 0, inputBytes.Length);
                    objCryptoStream.FlushFinalBlock();
                    objCryptoStream.Close();
                }
                encripted = ms.ToArray();
            }
            return encripted;
        }

        public string CryptToText(string text)
        {
            var encripted = Crypt(text);
            return Convert.ToBase64String(encripted);
        }

        public string Decrypt(string text)
        {
            var inputBytes = Convert.FromBase64String(text);
            return Decrypt(inputBytes);
        }

        public string Decrypt(byte[] crypto)
        {
            string decryptedString;
            var cripto = new RijndaelManaged();
            using (var ms = new MemoryStream(crypto))
            {
                using (var objCryptoStream = new CryptoStream(ms, cripto.CreateDecryptor(_key, _iv), CryptoStreamMode.Read))
                {
                    using (var sr = new StreamReader(objCryptoStream, true))
                    {
                        decryptedString = sr.ReadToEnd();
                    }
                }
            }
            return decryptedString;
        }        
    }
}
